package com.zb.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;
import java.util.Random;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zb.common.annotation.WriteLog;
import com.zb.common.exception.BusinessException;
import com.zb.common.po.enums.LogType;
import com.zb.common.po.enums.ResponseCode;
import com.zb.common.po.model.Menu;
import com.zb.common.po.model.SessionUser;
import com.zb.common.po.model.User;
import com.zb.common.po.vo.AjaxResponse;
import com.zb.common.utils.Constants;
import com.zb.service.MenuService;
import com.zb.service.UserService;

@Controller
@RequestMapping
public class IndexController {

    Logger logger = LoggerFactory.getLogger(IndexController.class);

    @Resource
    private MenuService menuService;

    @Resource
    private UserService userService;

    @RequestMapping(value = "/home.do")
    public String goAdd() throws ServletException, IOException {
        return "/page/home";
    }

    /**
     * 用户退出
     * 
     * @param request
     * @param response
     * @param session
     * @return
     */
    @RequestMapping(value = "/logout.do")
    public String logout(HttpServletRequest request,
            HttpServletResponse response, HttpSession session)
            throws ServletException {
        // 删除session
        Object obj = request.getSession().getAttribute(Constants.SESSION_KEY);
        if (null != obj) {
            request.getSession().removeAttribute(Constants.SESSION_KEY);
            request.getSession().invalidate();
        }
        // 重定向登录页面
        return "redirect:login.do";
    }

    @RequestMapping(value = "/login.do")
    public ModelAndView login(HttpSession session) throws ServletException,
            IOException {
        ModelAndView view = new ModelAndView("/page/login");
        return view;
    }

    @ResponseBody
    @RequestMapping("ajaxlogin.do")
    @WriteLog(opObject = "登陆", opDescription = "账号：#{#param0}", paramIndexes = { 1 }, logType = LogType.LOGIN)
    public AjaxResponse<?> ajaxlogin(HttpSession session, String account,
            String password, String authcode) {
        AjaxResponse<?> response = new AjaxResponse<Object>();
        try {
            if (!String.valueOf(session.getAttribute(Constants.VERIFYCODE))
                    .equalsIgnoreCase(authcode)) {
                response.setResponseCode(ResponseCode.CODEERROR);
                response.setErrorMsg("验证码错误");
                return response;
            }
            User user = userService.login(account, password);
            SessionUser sessionUser = new SessionUser();
            sessionUser.setUserId(user.getUserId());
            sessionUser.setUserName(user.getUserName());
            sessionUser.setRole(user.getRole());
            List<Menu> allMenuList = menuService.findAllMenuByRoles(user
                    .getRoles());
            sessionUser.setMenuList(allMenuList);
            session.setAttribute(Constants.SESSION_KEY, sessionUser);
            response.setResponseCode(ResponseCode.SUCCESS);
        } catch (BusinessException e) {
            logger.error("登录失败：{}", e);
            response.setResponseCode(ResponseCode.BUSINESSERROR);
            response.setErrorMsg(e.getMessage());
        } catch (Exception e) {
            logger.error("登录失败：{}", e);
            response.setResponseCode(ResponseCode.SERVERERROR);
            response.setErrorMsg(Constants.SYSTEMERRORMSG);
        }
        return response;
    }

    @RequestMapping(value = "/verifyCode.do")
    public void verifyCode(HttpServletResponse response, HttpSession session) {
        // 验证码图片的宽度。
        int width = 90;
        // 验证码图片的高度。
        int height = 28;
        // 验证码字符个数
        int codeCount = 4;
        int x = 0;
        // 字体高度
        int fontHeight;
        int codeY;
        char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
                'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
                'W', 'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9' };
        int codeLength = codeSequence.length;
        x = width / (codeCount);
        fontHeight = height - 2;
        codeY = height - 4;

        BufferedImage buffImg = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g = buffImg.createGraphics();
        // 创建一个随机数生成器类
        Random random = new Random();
        // 将图像填充为白色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);
        // 创建字体，字体的大小应该根据图片的高度来定。
        Font font = new Font("Fixedsys", Font.PLAIN, fontHeight);
        // 设置字体。
        g.setFont(font);
        // 画边框。
        g.setColor(Color.BLACK);
        g.drawRect(0, 0, width - 1, height - 1);
        // 随机产生160条干扰线，使图象中的认证码不易被其它程序探测到。
        g.setColor(Color.BLACK);
        for (int i = 0; i < 10; i++) {
            int _x = random.nextInt(width);
            int y = random.nextInt(height);
            int xl = random.nextInt(12);
            int yl = random.nextInt(12);
            g.drawLine(_x, y, x + xl, y + yl);
        }
        // randomCode用于保存随机产生的验证码，以便用户登录后进行验证。
        StringBuffer randomCode = new StringBuffer();
        int red = 0, green = 0, blue = 0;
        // 随机产生codeCount数字的验证码。
        for (int i = 0; i < codeCount; i++) {
            // 得到随机产生的验证码数字。
            String strRand = String.valueOf(codeSequence[random
                    .nextInt(codeLength)]);
            // 产生随机的颜色分量来构造颜色值，这样输出的每位数字的颜色值都将不同。
            red = random.nextInt(255);
            green = random.nextInt(255);
            blue = random.nextInt(255);
            // 用随机产生的颜色将验证码绘制到图像中。
            g.setColor(new Color(red, green, blue));
            g.drawString(strRand, i * x + 3, codeY);
            // 将产生的四个随机数组合在一起。
            randomCode.append(strRand);
        }
        // 将四位数字的验证码保存到Session中。
        session.setAttribute(Constants.VERIFYCODE, randomCode.toString());
        // 禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        // 将图像输出到Servlet输出流中。
        ServletOutputStream sos = null;
        try {
            sos = response.getOutputStream();
            ImageIO.write(buffImg, "jpeg", sos);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                if (null != sos) {
                    sos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    @RequestMapping(value = "/nourl.do")
    public ModelAndView nourl(HttpSession session) throws ServletException,
            IOException {
        ModelAndView view = new ModelAndView("page/nourl");
        return view;
    }

}
